import { resolve } from 'path'
import { defineConfig } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import Unocss from 'unocss/vite'
import AutoImport from 'unplugin-auto-import/vite'

const multiConfPlugin = () => {
  let configEnv: any
  return {
    name: 'young-multi-conf',
    enforce: 'post',
    configResolved: (config) => {
      configEnv = config.env
    },
    generateBundle(options, bundle) {
      const appid = configEnv.VITE_APPID
      console.log('🚀 ~ file: vite.config.ts:19 ~ multiConfPlugin ~ appid:', appid)
      const json = bundle['project.config.json']
      if (json?.source) {
        const jsonConf = JSON.parse(json.source)

        jsonConf.libVersion = '2.24.5'
        jsonConf.setting = {
          urlCheck: true,
          coverView: true,
          es6: true,
          postcss: true,
          lazyloadPlaceholderEnable: false,
          preloadBackgroundData: false,
          minified: true,
          autoAudits: false,
          uglifyFileName: false,
          uploadWithSourceMap: true,
          enhance: true,
          showShadowRootInWxmlPanel: true,
          packNpmManually: false,
          packNpmRelationList: [],
          minifyWXSS: true,
          useStaticServer: true,
          showES6CompileOption: false,
          checkInvalidKey: true,
          babelSetting: {
            ignore: [],
            disablePlugins: [],
            outputPath: '',
          },
          disableUseStrict: false,
          useCompilerPlugins: false,
          minifyWXML: true,
          useMultiFrameRuntime: true,
          ignoreUploadUnusedFiles: false,
          ignoreDevUnusedFiles: false,
        }
        jsonConf.appid = appid
        jsonConf.requiredPrivateInfos = ['getLocation']
        jsonConf.permission = {
          'scope.userLocation': {
            desc: '你的位置信息将用于获取附近的门店信息',
          },
        }

        json.source = JSON.stringify(jsonConf, null, 2)
      }
      // console.log("🚀 ~ file: vite.config.ts:18 ~ generateBundle ~ bundle:", json)
      // 处理生成的输出文件
    },
  }
}

// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      '@/': `${resolve(__dirname, 'src')}/`,
    },
  },
  plugins: [
    uni(),

    // https://github.com/antfu/unocss
    Unocss(),

    // https://github.com/antfu/unplugin-auto-import
    AutoImport({
      imports: ['vue', 'uni-app', 'pinia'],
      dts: true,
      vueTemplate: true,
    }),

    multiConfPlugin(),
  ],
})
